import shelve
import http.cookies
import datetime
from typing import *

class CookieStore:
    @staticmethod
    def get_cookie_str():
        try:
            with shelve.open('data/login') as db:
                cookie_data = db.get('cookie')
                refresh_token = db.get('refresh_token')
                if not cookie_data:
                    return ''
                
                # 处理不同格式的cookie数据
                if isinstance(cookie_data, str):
                    # 旧格式字符串
                    cookie = http.cookies.SimpleCookie()
                    cookie.load(cookie_data)
                elif isinstance(cookie_data, http.cookies.SimpleCookie):
                    # SimpleCookie对象
                    cookie = cookie_data
                else:
                    return ''
                
                # 从SimpleCookie提取键值对
                cookie_items = [(key, cookie[key].value) for key in cookie.keys()]
                uid = cookie['DedeUserID'].value
                cookie_str = '; '.join([f"{key}={value}" for key, value in cookie_items])
                return cookie_str,uid,refresh_token
        except Exception as e:
            print(f"Error reading cookie: {e}")
            return ''

    @staticmethod
    def get_cookie_token() -> Tuple[dict, str]:
        try:
            with shelve.open('data/login') as db:
                cookie_data = db.get('cookie')
                refresh_token = db.get('refresh_token')
                if not cookie_data:
                    return dict(), ''

                # 处理不同格式的cookie数据
                if isinstance(cookie_data, str):
                    # 旧格式字符串
                    cookie = http.cookies.SimpleCookie()
                    cookie.load(cookie_data)
                elif isinstance(cookie_data, http.cookies.SimpleCookie):
                    # SimpleCookie对象
                    cookie = cookie_data
                else:
                    return dict(), ''

                # 从SimpleCookie提取键值对
                cookie_items = {key: cookie[key].value for key in cookie.keys()}
                return cookie_items, refresh_token
        except Exception as e:
            print(f"Error reading cookie: {e}")
            return dict(), ''

    @staticmethod
    def set_cookie_and_token(simple_cookie,refresh_token):
        with shelve.open('data/login') as db:
            db['cookie'] = simple_cookie
            db['date'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            db['refresh_token'] = refresh_token
        pass
